package com.tangly.codeing.controller;

import com.tangly.codeing.model.dto.SysRoleDto;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.tangly.codeing.model.SysRolePrivilege;
import com.tangly.codeing.service.SysRolePrivilegeService;
import com.tangly.codeing.utils.PageInfo;
import com.tangly.codeing.utils.ReturnT;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * 角色权限表
 * @author tangbing
 * @date 2019-05-30
 */
@RestController
@RequestMapping("sysRolePrivilege")
public class SysRolePrivilegeController extends BaseController{

    @Resource
    private SysRolePrivilegeService sysRolePrivilegeService;

    /**
    * 新增
    */
    @PostMapping("/insert")
    public ReturnT<String> insert(@RequestBody SysRolePrivilege sysRolePrivilege){
        return sysRolePrivilegeService.insert(sysRolePrivilege);
    }

    /**
    * 删除
    */
    @RequestMapping("/delete/{id}")
    public ReturnT<String> delete(@PathVariable("id") Long id){
        return sysRolePrivilegeService.delete(id);
    }

    /**
    * 批量删除
    */
    @GetMapping("/batchDelete")
    public ReturnT<String> batchDelete(@RequestParam("ids") String ids) {
       String[] split = ids.split(",");
       return sysRolePrivilegeService.batchDelete(Arrays.asList(split));
    }

    /**
    * Load查询
    */
    @GetMapping("/load/{id}")
    public ReturnT<Object> load(@PathVariable("id") Long id){
        return new ReturnT<>(sysRolePrivilegeService.load(id));
    }

    /**
    * 分页查询
    */
    @PostMapping("/pageList")
    public ReturnT<Object> pageList(@RequestBody PageInfo pageInfo) {
        ReturnT<Object> validateRes = validateParam(pageInfo);
        if (validateRes != null) {
            return validateRes;
        }
        return new ReturnT<>(sysRolePrivilegeService.pageList(pageInfo));
    }

    /**
     * 更新
     */
    @PostMapping("/updatePermission")
    public ReturnT<String> updatePermission(@RequestBody @Validated SysRoleDto sysRoleDto, BindingResult result) {
        if (result.hasErrors()) {
            FieldError fieldError = result.getFieldError();
            return new ReturnT<>(ReturnT.FAIL_CODE, fieldError.getDefaultMessage());
        }
        if (sysRoleDto.getPermissions().size() == 0) {
            return new ReturnT<>(ReturnT.FAIL_CODE, "角色资源不能为空");
        }
        return sysRolePrivilegeService.update(sysRoleDto);
    }
}
